package lc20240523;

import lc20240521.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Demo2 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(7);
        root.left = new TreeNode(3);
        root.right = new TreeNode(15);
        root.left.left=new TreeNode(4);
        Demo2 demo2 = new Demo2();
//        System.out.println(demo2.countNodes(root));
        System.out.println(demo2.countNodes1(root));
    }

    public int countNodes(TreeNode root) {
        if (root == null)
            return 0;
        if (root.left == null && root.right == null) {
            return 1;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int count = 0;
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            count++;
            if (cur.left != null) {
                queue.add(cur.left);
            }
            if (cur.right != null) {
                queue.add(cur.right);
            }
        }
        return count;
    }

    public int countNodes1(TreeNode root) {
        if (root == null)
            return 0;
        int h = 0;
        TreeNode cur = root;
        //计算高度
        while (cur != null) {
            cur = cur.left;
            h++;
        }
        h=h-1; //高度减一，前n-1层
        System.out.println(h);
        int left = 1;
        int right = (1 << h) - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (exists(mid, h, root)) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return (1 << h) - 1 + left;
    }

    public boolean exists(int index, int h, TreeNode node) {
        int left = 0;
        int right = (1 << h) - 1;
        for (int i = 0; i < h; i++) {
            int mid = (left + right) / 2;
            if (index <= mid) {
                node = node.left;
                right = mid;
            } else {
                node = node.right;
                left = mid + 1;
            }
        }
        return node != null;
    }
}
